import pygame, random
from .alien import Alien
from pygame.sprite import Group
from .eventCenter import EventCenter

class AlintFactory(EventCenter):
    ''' 外星人工厂 '''
    
    def __init__(self, screen, config):
        
        self.screen = screen
        self.alints = Group()
        self.config = config
        self.Max = 10
        self.screen_rect = screen.get_rect()    
        self.eventMap = {
            "gameUpdate": self.update,
            "gameBlit": self.blitme,
            "removeAlint": self.remove 
        }
        
        self.bindEvent()
    
    def start(self):
        self.createAlien
        self.tbox.init()


    def createAlien(self):
        
        x = self.screen_rect.right - random.random() * self.config['x']
        y = random.random() * self.config['y'] + 100

        alien = Alien(self.screen,x,y)
        self.alints.add(alien)
        
    def update(self, event):
        
        alints = self.alints
        
        self.alienBoundary()

        if len(alints) < self.Max:
            self.createAlien() 

        for item in alints:
            item.update()
            
    
    def blitme(self, event):
        
        for item in self.alints:
            item.blitme()

    def alienBoundary(self):
        
        for item in self.alints:
            if item.rect.x < 0:
                self.remove(item)
    

    def remove(self, alien):
        
        if alien in self.alints:
            self.alints.remove(alien)
    
    def bindEvent(self):
        
        for eventName, fn in self.eventMap.items():
            self.registered(eventName, fn)